﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TA.JSON
{
	public static class _IJsonReaderExtensions
	{
		/// <summary>
		/// Verifies the current token and moves to the next.
		/// </summary>
		/// <param name="token"></param>
		public static void Read(this IJsonReader This, JsonToken token)
		{
			This.Expect(token);
			This.Read();
		}
		/// <summary>
		/// Verifies the current token.
		/// </summary>
		/// <param name="token"></param>
		public static void Expect(this IJsonReader This, JsonToken token)
		{
			if (This.TokenType != token)
				throw new JsonException("Expected " + token + " but found " + This.TokenType);
		}
		/// <summary>
		/// Deserializes an object, using the specified delegate for each property.
		/// </summary>
		/// <param name="oneProperty"></param>
		public static void DeserializeObject(this IJsonReader This, Action<string, IJsonReader> oneProperty)
		{
			This.Read(JsonToken.StartObject);

			while (This.TokenType == JsonToken.PropertyName)
			{
				string prName = (string)This.Value;
				This.Read();

				oneProperty(prName, This);
				This.Read();
			}

			This.Expect(JsonToken.EndObject);
		}
		/// <summary>
		/// Deserializes an array, using the specified delegate for each item.
		/// </summary>
		/// <param name="oneItem"></param>
		public static void DeserializeArray(this IJsonReader This, Action<int, IJsonReader> oneItem)
		{
			This.Read(JsonToken.StartArray);

			int index = 0;
			while (This.TokenType != JsonToken.EndArray)
			{
				oneItem(index, This);
				This.Read();

				++index;
			}

			This.Expect(JsonToken.EndArray);
		}

	}
}
